/**
 * 历史记录
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, DatePicker, Pagination, Button, Timeline, Card, Divider } from 'antd';
import React, { useState, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import styles from './index.less';
import moment from 'moment';

import {
  getHistory
} from '../service';
import { Const } from '../../Const';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;

class PrivateData {
  static paramsObj = {
    current: 1,
    pageSize: 10
  };
  // 少收、破损、内物缺失 - 事故单信息
  static accidentLessDetail = [
    { text: '发生事故行李件数', value: 'accidentPkgCount', arr: [1, 2, 6, 7] },
    { text: '发生事故行李总重量', value: 'accidentPkgWeight', arr: [1, 2, 6, 7] },
    { text: '飞机号', value: 'planeCode', arr: [1, 2, 6, 7] },
    { text: '飞机型号', value: 'acType', arr: [1, 2, 6, 7] },
    { text: '客票上行李总件数', value: 'tktPkgCount', arr: [1, 2, 6, 7] },
    { text: '客票上行李总重量', value: 'tktPkgWeight', arr: [1, 2, 6, 7] },
    { text: '服务航站', value: 'serviceCity', arr: [1, 2, 6, 7] },
    { text: '事故原因', value: 'accidentReason', isMap: 'accidentReasonMap', arr: [1, 2, 6, 7] },
    { text: '赔偿总金额', value: 'payMoney', arr: [1, 2, 6, 7] },
    { text: '录入航站三字码', value: 'enterTerminal', arr: [1, 2, 6, 7] },
    { text: '录入航站联系电话', value: 'enterTerminalPhone', arr: [1, 2, 6, 7] },
    { text: '事故单生成时间', value: 'createTime', arr: [1, 2, 6, 7] },
    { text: '录入人', value: 'createUser', arr: [1, 2, 6, 7] },
    { text: '责任机场', value: 'dutyTerminal', arr: [1, 2, 6, 7] },
    { text: '快递总费用', value: 'transportPay', arr: [1, 2, 6, 7] },
    { text: '结案状态', value: 'pkgStatus', arr: [1, 2, 6, 7] },
    { text: '结案时间', value: 'closeTime', arr: [1, 2, 6, 7] },
    { text: '结案人', value: 'closeUser', arr: [1, 2, 6, 7] },
    { text: '航班日期', value: 'flightDate', arr: [1, 2, 6, 7] },
    { text: '航班号', value: 'flightNo', arr: [1, 2, 6, 7] },
    { text: '超重行李费用', value: 'pkgOverWeightPrice', arr: [1, 2, 6, 7] },
    { text: '超重行李重量', value: 'pkgOverWeight', arr: [1, 2, 6, 7] },
    { text: '事故单状态', value: 'status', isMap: 'jieAnStatusMap', arr: [1, 2, 6, 7] },
    { text: '是否发起结案赔偿', value: 'closePayment', arr: [1, 2, 6, 7] },
    { text: '是否发起临时赔偿', value: 'tempPayment', arr: [1, 2, 6, 7] },
    { text: '已赔付金额', value: 'receivePayment', arr: [1, 2, 6, 7] },
    { text: '旅客航程', value: 'segment', arr: [1, 2, 6, 7] },
    { text: '旅客目的站三字码', value: 'dst', arr: [1, 2, 6, 7] },
    { text: '旅客证件号', value: 'idNo', arr: [1, 2, 6, 7] },
    { text: '旅客证件类型', value: 'idType', isMap: 'idTypeMap', arr: [1, 2, 6, 7] },
    { text: '舱位', value: 'cabin', arr: [1, 2, 6, 7] },
    { text: '旅客始发站三字码', value: 'org', arr: [1, 2, 6, 7] },
    { text: '旅客姓名', value: 'paxName', arr: [1, 2, 6, 7] },
    { text: '旅客姓名缩写', value: 'paxInitials', arr: [1, 2, 6, 7] },
    { text: '联系方式1', value: 'recipientPhoneFirst', arr: [1, 2, 6, 7] },
    { text: '联系方式2', value: 'recipientPhoneSecond', arr: [1, 2, 6, 7] },
    { text: '客票号', value: 'tktNo', arr: [1, 2, 6, 7] },
    { text: '收件人地址', value: 'recipientAddress', arr: [1, 2, 6, 7] },
    { text: '收件人姓名', value: 'expressRecipient', arr: [1, 2, 6, 7] },
    { text: '少收类型', value: 'littlePkgType', isMap: 'littlePkgTypeMap', arr: [2, 6] },
    { text: '事故提醒', value: 'remindDay', unit: '天(自然日)', arr: [2, 6] },
    { text: '备注', value: 'remark', arr: [1, 2, 6, 7] },
    { text: '未赔付金额', value: 'notPayment', arr: [1, 2, 6, 7] },
  ];
  // 多收 - 事故单信息
  static accidentMoreDetail = [
    // { text: '飞机型号', value: 'acType', arr: [3] },
    // { text: '行李航线', value: 'pkgSegment', arr: [3] },
    // { text: '行李牌上目的地', value: 'pkgDst', arr: [3] },
    { text: '行李颜色', value: 'pkgColor', arr: [3] },
    { text: '行李描述', value: 'pkgContent', arr: [3] },
    { text: '行李牌号', value: 'pkgNo', arr: [3] },
    { text: 'WT编号', value: 'wtCode', arr: [3] },
    // { text: '客票上行李总件数', value: 'tktPkgCount', arr: [3] },
    { text: '客票上行李总重量', value: 'tktPkgWeight', arr: [3] },
    { text: '行李类别', value: 'pkgType', arr: [3] },
    { text: '录入航站联系电话', value: 'enterTerminalPhone', arr: [3] },
    { text: '事故单生成时间', value: 'createTime', arr: [3] },
    { text: '录入人', value: 'createUser', arr: [3] },
    { text: '结案状态', value: 'pkgStatus', arr: [3] },
    { text: '航班日期', value: 'flightDate', arr: [3] },
    { text: '航班号', value: 'flightNo', arr: [3] },
    // { text: '作废状态', value: 'deleteName', arr: [3] },
    { text: '旅客航程', value: 'segment', arr: [3] },
    { text: '旅客目的站三字码', value: 'dst', arr: [3] },
    { text: '旅客证件号', value: 'idNo', arr: [3] },
    { text: '旅客证件类型', value: 'idType', isMap: 'idTypeMap', arr: [3] },
    { text: '舱位', value: 'cabin', arr: [3] },
    { text: '旅客始发站三字码', value: 'org', arr: [3] },
    { text: '旅客姓名', value: 'paxName', arr: [3] },
    // { text: '联系方式1', value: 'recipientPhoneFirst', arr: [3] },
    // { text: '联系方式2', value: 'recipientPhoneSecond', arr: [3] },
    { text: '客票号', value: 'tktNo', arr: [3] },
    // { text: '备注', value: 'remark', arr: [3] },
  ];
  // 行李信息
  static pkgDetail = [
    { text: '行李航线', value: 'pkgSegment', arr: [1, 2, 6, 7] },
    { text: '行李牌上目的地', value: 'pkgDst', arr: [1, 2, 6, 7] },
    { text: '行李颜色', value: 'pkgColor', arr: [1, 2, 6, 7] },
    { text: '行李描述', value: 'pkgContent', arr: [1, 2, 6, 7] },
    { text: '行李牌号', value: 'pkgNo', arr: [1, 2, 6, 7] },
    { text: '行李备注', value: 'pkgRemark', arr: [1, 2, 6, 7] },
    { text: '行李类别', value: 'pkgType', arr: [1, 2, 6, 7] },
    { text: '行李重量', value: 'pkgWeight', arr: [1, 2, 6, 7] },
    { text: '逾重行李票号', value: 'overweightTktNo', arr: [1, 2, 6, 7] },
    { text: '破损类型', value: 'damageType', isMap: 'damageTypeMap', arr: [1, 7] },
    { text: '破损部位', value: 'damagePart', isMap: 'damagePartMap', arr: [1, 7] },
    { text: '破损程度', value: 'damageLevel', isMap: 'damageLevelMap', arr: [1, 7] },
    { text: '缺失物品描述', value: 'lossItemsContent', arr: [6] },
  ];
  static dealDetail = (item, itemLast, historyStatus) => {
    let detail = {};
    for (let key in item) {
      if (key === 'historyStatus' || key === 'pkgDetailInfoList') continue;
      const itemValue = item[key] || '';
      const itemLastValue = itemLast[key] || '';
      detail[key] = {
        value: itemValue,
        isRed: +historyStatus === 1 ? (itemValue !== itemLastValue) : false
      }
    }
    // console.log(detail, 'detaildetaildetail');
    return detail;
  };
  static dealPkgDetail = (item, itemLast, historyStatus) => {
    let pkgDetail = [];
    let itemArr = item['pkgDetailInfoList'] || [];
    let itemLastArr = itemLast['pkgDetailInfoList'] || [];
    for (let m of itemArr) {
      let mItem = {};
      let isSame = false;
      for (let n of itemLastArr) {
        if (n.id === m.id) {
          isSame = true;
          mItem = PrivateData.dealDetail(m, n, historyStatus);
        }
      }
      if (!isSame) mItem = PrivateData.dealDetail(m, {}, historyStatus);
      pkgDetail.push(mItem)
    }
    // console.log(pkgDetail, 'pkgDetailpkgDetailpkgDetail');
    return pkgDetail;
  };
  static dealDetailText = (item, data, ownerType) => {
    let val = data[item.value]?.value;
    if (item.isMap) {
      if (item.value === 'damageType' || item.value === 'damagePart') {
        let arr = (val ? val.split(',') : []) || [];
        let arrName = [];
        for (let i of arr) {
          arrName.push(Const[item.isMap][i]?.text || '');
        }
        return arrName.join(',');
      } else {
        return Const[item.isMap][val]?.text || '';
      }
    } else {
      // 破损不显示值
      if (item.value === 'tempPayment') {
        if (+ownerType === 1 || +ownerType === 7) {
          return '';
        } else {
          return (val || '') + (item.unit || '');
        }
      } else if (item.value === 'pkgStatus') {
        if (+val === 1) return '已结案';
        return '未结案';
      } else {
        return (val || '') + (item.unit || '');
      }
    }
  };
}

const HistoryRecord = props => {

  const { modalVisible, onCancel, form, onSubmit, accidentId, ownerType } = props;

  // todo: historyStatus 0创建 1修改

  const [historyList, setHistoryList] = useState([]); // 列表
  const [total, setTotal] = useState(0); // 总数
  const [detailData, setDetailData] = useState({}); // 详情
  const [detailPkgData, setDetailPkgData] = useState([]); // 行李详情
  const [currentIndex, setCurrentIndex] = useState(0);

  // 历史记录列表
  const { run: runGetHistory } = useRequest(params => getHistory(params), {
    manual: true,
    onSuccess (res) {
      console.log(res, '历史记录列表');
      let data = res || {};
      let arr = data.data || [];
      setTotal(data.total || 0);
      setHistoryList(arr);
      if (arr.length !== 0) {
        let item = JSON.parse(arr[0].accidentContent) || {};
        let itemLast = JSON.parse(arr[0].accidentContentLast) || {};
        let detail = PrivateData.dealDetail(item, itemLast, arr[0].historyStatus);
        let pkgDetail = PrivateData.dealPkgDetail(item, itemLast, arr[0].historyStatus);
        if (+ownerType === 3) {
          if (pkgDetail && pkgDetail.length >= 1) {
            setDetailData({
              ...detail,
              ...pkgDetail[0]
            });
          } else {
            setDetailData({
              ...detail,
            });
          }
        } else {
          setDetailData({
            ...detail
          });
          setDetailPkgData([
            ...pkgDetail
          ]);
        }
      }
    }
  })

  useEffect(() => {
    if (modalVisible) {
      runGetHistory({
        accidentId,
        current: 1,
        pageSize: 10
      })
    } else {
      PrivateData.paramsObj = {
        current: 1,
        pageSize: 10
      };
    }
  }, [modalVisible, accidentId, ownerType]);

  // 点击查看详情
  const timelineClick = useCallback(index => {
    if (index === currentIndex) return;
    setCurrentIndex(index);
    let item = JSON.parse(historyList[index].accidentContent) || {};
    let itemLast = JSON.parse(historyList[index].accidentContentLast) || {};
    let detail = PrivateData.dealDetail(item, itemLast, historyList[index].historyStatus);
    let pkgDetail = PrivateData.dealPkgDetail(item, itemLast, historyList[index].historyStatus);
    if (+ownerType === 3) {
      if (pkgDetail && pkgDetail.length >= 1) {
        setDetailData({
          ...detail,
          ...pkgDetail[0]
        });
      } else {
        setDetailData({
          ...detail,
        });
      }
    } else {
      setDetailData({
        ...detail
      });
      setDetailPkgData([
        ...pkgDetail
      ]);
    }
  }, [historyList, currentIndex, ownerType]);

  // 分页改变
  const paginationChange =useCallback((page, pageSize) => {
    console.log(page, pageSize, '分页改变');
    PrivateData.paramsObj.current = page;
    runGetHistory({
      ...PrivateData.paramsObj,
      accidentId,
    })
  }, [accidentId]);

  // 查询
  const searchList = useCallback(() => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      let arr = ['startTime', 'endTime'];
      for (let item of arr) {
        if (fieldsValue[item] && fieldsValue[item].isValid()) {
          fieldsValue[item] = fieldsValue[item].format(Const.format);
        }
      }
      runGetHistory({
        ...PrivateData.paramsObj,
        ...fieldsValue,
        accidentId,
      })
    })
  }, [form, accidentId]);

  // 重置
  const resetList = useCallback(() => {
    form.setFieldsValue({
      startTime: '',
      endTime: '',
    })
    PrivateData.paramsObj.startTime = '';
    PrivateData.paramsObj.endTime = '';
    runGetHistory({
      ...PrivateData.paramsObj,
      accidentId,
    })
  }, [form, accidentId]);

  const okHandle = useCallback(() => {
    onSubmit();
  }, []);

  return (
    <Modal
      destroyOnClose
      title="历史记录"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={onCancel}
      width={800}
      maskClosable={false}
    >
      <div className={styles.historyRecordContent}>
        <div className={styles.topTitle}>
          <FormItem {...Const.formLayout} label="开始时间">
            {form.getFieldDecorator('startTime', {
              rules: [],
              initialValue: ''
            })(
              <DatePicker
                format={Const.format}
                placeholder="请选择日期"
                style={{ width: '100%' }} />
            )}
          </FormItem>
          <FormItem {...Const.formLayout} label="结束时间">
            {form.getFieldDecorator('endTime', {
              rules: [],
              initialValue: ''
            })(
              <DatePicker
                format={Const.format}
                placeholder="请选择日期"
                style={{ width: '100%' }} />
            )}
          </FormItem>
          <Button type="primary" style={{ marginRight: '10px' }} onClick={searchList}>查询</Button>
          <Button type="primary" onClick={resetList}>重置</Button>
        </div>
        <div className={styles.middleContent}>
          <div className={styles.middleContentLeft}>
            <Timeline>
              {historyList.map((item, index) => (
                <Timeline.Item key={index}>
                  <Button
                    className={styles.timelineItem}
                    onClick={() => timelineClick(index)}>
                    {+item.historyStatus === 1 ? '修改人' : '录入人'}:{item.createUser} {item.createTime}
                  </Button>
                </Timeline.Item>
              ))}
            </Timeline>
          </div>
          <div className={styles.middleContentRight}>
            <div className={styles.middleContentRightTitle}>历史详情</div>
            <div className={styles.middleContentRightBox}>
              <Divider>事故单信息</Divider>
              {(+ownerType === 3 ? PrivateData.accidentMoreDetail : PrivateData.accidentLessDetail).map((item, index) => {
                if (item.arr.indexOf(+ownerType) > -1) {
                  return <div key={index} className={styles.middleContentRightBoxItem}>
                    <span className={detailData[item.value]?.isRed ? styles.middleContentRightBoxRed : ''}>{item.text}：</span>
                    {PrivateData.dealDetailText(item, detailData, ownerType)}
                  </div>
                }
              })}
              {+ownerType !== 3 && detailPkgData.map((item, index) => (
                <>
                  <Divider>{`行李${index + 1}信息`}</Divider>
                  {PrivateData.pkgDetail.map((m, n) => {
                    if (m.arr.indexOf(+ownerType) > -1) {
                      return <div key={`${index}-${n}`} className={styles.middleContentRightBoxItem}>
                        <span className={item[m.value]?.isRed ? styles.middleContentRightBoxRed : ''}>{m.text}：</span>
                        {PrivateData.dealDetailText(m, item, ownerType)}
                      </div>
                    }
                  })}
                </>
              ))}
            </div>
          </div>
        </div>
        <div className={styles.paginationContent} onChange={paginationChange}>
          <Pagination defaultCurrent={1} total={total} />
        </div>
      </div>
    </Modal>
  )
}

export default Form.create()(HistoryRecord);
